package com.hogocloud.corelibrary.utils

import android.Manifest
import android.app.Activity
import android.app.Service
import android.content.Context
import android.content.pm.PackageManager
import android.net.wifi.WifiManager
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.util.DisplayMetrics
import android.view.WindowManager
import android.widget.Toast
import androidx.core.app.ActivityCompat
import java.net.InetAddress
import java.net.NetworkInterface
import java.net.SocketException

/**
 * 设备相关信息
 * @author daydream
 */
object DeviceUtils {

    var DEVICE_RELEASE_VERSION = Build.VERSION.RELEASE // 获取版本号

    var DEVICE_MODEL = Build.MODEL            // 获取手机型号
    var DEVICE_BRAND = Build.BRAND            // 获取手机厂商

    var DEVICE_ID: String = ""

    var MAC_ADDRESS: String = ""

    val isBrandXiaoMi: Boolean
        get() = "xiaomi".equals(Build.BRAND, ignoreCase = true) || "xiaomi".equals(
            Build.MANUFACTURER,
            ignoreCase = true
        )

    val isBrandHuawei: Boolean
        get() = "huawei".equals(Build.BRAND, ignoreCase = true) || "huawei".equals(
            Build.MANUFACTURER,
            ignoreCase = true
        )

    val isBrandMeizu: Boolean
        get() = "meizu".equals(Build.BRAND, ignoreCase = true) || "meizu".equals(
            Build.MANUFACTURER,
            ignoreCase = true
        ) || "22c4185e".equals(Build.BRAND, ignoreCase = true)

    val isBrandOppo: Boolean
        get() = "oppo".equals(Build.BRAND, ignoreCase = true) || "oppo".equals(Build.MANUFACTURER, ignoreCase = true)

    val isBrandVivo: Boolean
        get() = "vivo".equals(Build.BRAND, ignoreCase = true) || "vivo".equals(Build.MANUFACTURER, ignoreCase = true)

    fun init(context: Context) {

        val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        if (ActivityCompat.checkSelfPermission(
                context,
                Manifest.permission.READ_PHONE_STATE
            ) != PackageManager.PERMISSION_GRANTED
        ) {

            return
        }
        DEVICE_ID = if (!TextUtils.isEmpty(tm.deviceId)) {
            tm.deviceId
        } else {
            // pad 设备,没有device_id,给个默认的id
            "868734026370770"
        }

        val wifi = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
        MAC_ADDRESS = wifi.connectionInfo.macAddress
    }

    fun getLocalIpAddress(context: Context): String? {
        try {
            val en = NetworkInterface.getNetworkInterfaces()
            while (en.hasMoreElements()) {
                val intf = en.nextElement() as NetworkInterface
                val enumIpAddr = intf.inetAddresses
                while (enumIpAddr.hasMoreElements()) {
                    val inetAddress = enumIpAddr.nextElement() as InetAddress
                    if (!inetAddress.isLoopbackAddress && !inetAddress.isLinkLocalAddress) {
                        return inetAddress.hostAddress
                    }
                }
            }
        } catch (ex: SocketException) {
            Toast.makeText(context, ex.message, Toast.LENGTH_SHORT).show()
        }

        return null
    }

    fun checkPermission(context: Context?, permission: String): Boolean {
        var result = false
        if (context == null) {
            return result
        }
        if (Build.VERSION.SDK_INT >= 23) {
            result = try {
                val clazz = Class.forName("android.content.Context")
                val method = clazz.getMethod("checkSelfPermission", String::class.java)
                val rest = method.invoke(context, permission) as Int
                rest == PackageManager.PERMISSION_GRANTED
            } catch (e: Throwable) {
                false
            }

        } else {
            val pm = context.packageManager
            if (pm.checkPermission(permission, context.packageName) == PackageManager.PERMISSION_GRANTED) {
                result = true
            }
        }
        return result
    }

    /**
     * getScreenWidth:得到屏幕宽度(像素点数). <br></br>
     *
     * @return
     */
    fun getScreenWidth(context: Context): Int {
        return getDisplayMetrics(context).widthPixels
    }

    /**
     * getScreenHeight:得到屏幕高度(像素点数). <br></br>
     *
     * @return
     */
    fun getScreenHeight(context: Context): Int {
        return getDisplayMetrics(context).heightPixels
    }

    /**
     * getDensity:得到像素密度 <br></br>
     *
     * @return
     */
    fun getDensity(context: Context): Float {
        return getDisplayMetrics(context).density
    }

    /**
     * getDensityDpi:得到每英寸的像素点数<br></br>
     *
     * @return
     */
    fun getDensityDpi(context: Context): Int {
        return getDisplayMetrics(context).densityDpi
    }

    /**
     * getDisplayMetrics:返回DisplayMetrics对象，以方便得到屏幕相关信息. <br></br>
     *
     * @param context
     * @return
     */
    private fun getDisplayMetrics(context: Context): DisplayMetrics {
        val dm = DisplayMetrics()
        try {
            val manager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val display = manager.defaultDisplay
            if (display != null) {
                display.getMetrics(dm)
            } else {
                dm.setToDefaults()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return dm
    }

    fun vibrate(activity: Activity, milliseconds: Long = 100) {
        when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> VibrationEffect.createOneShot(milliseconds, VibrationEffect.DEFAULT_AMPLITUDE)
            else -> {
                val vib = activity.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator
                vib.vibrate(milliseconds)
            }
        }
    }
}
